package com.validation.constraints;

import java.io.UnsupportedEncodingException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class BytesLengthValidator implements ConstraintValidator<BytesLength, String>{

	private String encoding;
    private int maxLength;
	
	/**{@inheritDoc}
	 * @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
	 */
	public void initialize(final BytesLength constraintAnnotation) {
		encoding = constraintAnnotation.encoding();
		maxLength = constraintAnnotation.max();
		validateParameters();
		
	}

	private void validateParameters() {
		if(maxLength< 0 ) {
			throw new IllegalArgumentException( "The max parameter cannot be negative." );
		}
		
	}

	/**{@inheritDoc}
	 * @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
	 */
	public boolean isValid(final String value, final ConstraintValidatorContext context) {
		if (value == null)
			return true;

		try {
			if (value.getBytes(encoding).length < maxLength)
				return true;
			else
				return false;
		} catch (final UnsupportedEncodingException e) {
			// ignore
		}

		return false;
	}
	
	

}
